package logic

import (
	"context"
	"strings"

	"server-go/rpc/reward/internal/models"
	"server-go/rpc/reward/internal/svc"
	"server-go/rpc/reward/internal/util"
	"server-go/rpc/reward/types/reward"

	"github.com/zeromicro/go-zero/core/logx"
)

type DoForgetPasswdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDoForgetPasswdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DoForgetPasswdLogic {
	return &DoForgetPasswdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 忘记密码模块开始
func (l *DoForgetPasswdLogic) DoForgetPasswd(in *reward.DoForgetPasswdInput) (*reward.DoForgetPasswdOutput, error) {
	out := &reward.DoForgetPasswdOutput{}
	usersDao := &models.UsersDao{Email: in.Email}
	if err := usersDao.First(l.svcCtx.Db); err != nil {
		return out, err
	}
	if usersDao.Id == 0 {
		out.EmailError = true
		return out, nil
	}
	rewardCode, err := util.RedisGet(l.svcCtx.Redis, in.Email)
	if err != nil {
		return out, err
	}
	if !strings.EqualFold(in.Captcha, rewardCode) {
		out.CaptchaError = true
		return out, nil
	}
	usersDao.Password = in.Password
	tx := l.svcCtx.Db.Begin()
	if err := usersDao.Update(tx); err != nil {
		tx.Rollback()
		return out, err
	}
	tx.Commit()
	out.Success = true
	return out, nil
}
